package test.com.sms.selenium.sms.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.sms.common.util.FileUtil;

import test.com.sms.selenium.framework.SmsSeleniumTestAbstract;
import test.com.sms.selenium.framework.SeleniumPageUtil;
import test.com.sms.selenium.util.SeleniumUtil;

public class SmsLoginPageUtil extends SeleniumPageUtil 
{
	
	private static final Properties environmentProperties = new Properties();
	
	static
	{
		InputStream is = null;
		try
		{
			is = new FileInputStream (FileUtil.getFile("configuration/testenvironment.properties", SmsSeleniumTestAbstract.class));
			environmentProperties.load(is);
		}
		catch (Exception e)
		{
			
		}
		finally
		{
			try{is.close();}catch(Exception ex){}
		}
	}
	
	protected static final String SMS_ROOT_URL = 
			environmentProperties.getProperty("sms.protocol", "http").trim() + "://" + 
			environmentProperties.getProperty("sms.host", "sms-selenium.prismpoint.net").trim() + ":" + 
			environmentProperties.getProperty("sms.port", "80").trim() + "/" + 
			environmentProperties.getProperty("sms.root.url", "").trim();
	
	private static final String USER_ID = environmentProperties.getProperty("sms.userid", "smstest"); 
	private static final String USER_PASSWORD = environmentProperties.getProperty("sms.password", "123456");
	
	// WebElement By
	public static final By LOGIN_INPUT_USERNAME = By.name("j_username");
	public static final By LOGIN_INPUT_PASSWORD = By.name("j_password");
	public static final By LOGIN_BUTTON_LOGIN = By.name("submit");
	public static final By LOGIN_BUTTON_RESET = By.name("reset");
	public static final By LOGIN_CHECKBOX_AUTO_LOGIN = By.name("_spring_security_remember_me");
	
	// get elements by methods
	public final static WebElement getLoginInputUsername(){
		return SeleniumUtil.getCachedElement(LOGIN_INPUT_USERNAME);
	}
	
	public final static WebElement getLoginInputPassword(){
		return SeleniumUtil.getCachedElement(LOGIN_INPUT_PASSWORD);
	}
	
	public final static WebElement getLoginButtonLogin(){
		return SeleniumUtil.getCachedElement(LOGIN_BUTTON_LOGIN);
	}
	
	public final static WebElement getLoginButtonReset(){
		return SeleniumUtil.getCachedElement(LOGIN_BUTTON_RESET);
	}
	
	
	public final static WebElement getLoginCheckboxAutoLogin(){
		return SeleniumUtil.getCachedElement(LOGIN_CHECKBOX_AUTO_LOGIN);
	}
	
	/** trigger login*/
	public final static void login() {
		SeleniumUtil.get(SMS_ROOT_URL);
		SeleniumUtil.selectDefaultContent();
		SeleniumUtil.sendKeys(getLoginInputUsername(), USER_ID);
		SeleniumUtil.sendKeys(getLoginInputPassword(), USER_PASSWORD);
		SeleniumUtil.click(SeleniumUtil.getCachedElement(LOGIN_CHECKBOX_AUTO_LOGIN));
		SeleniumUtil.click(getLoginButtonLogin());
		// goto homepage
		SmsHomePageUtil.waitForPageToLoad();
	}
}
